<template>
  <div>
    <div class="level-content">
      <el-form
        :model="levelForm"
        :rules="levelRules"
        ref="levelForm"
        label-width="120px"
        :status-icon="false"
        label-position="right">
        <el-divider>基础设置</el-divider>
        <el-form-item label="等级名称" prop="level_name">
          <el-input v-model="levelForm.level_name" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="level_icon">
          <el-upload
            :action="MixinUploadApi"
            :headers="MixinAccessToken"
            list-type="picture"
            :on-success="uploadSuccess"
            :on-remove="delImgEvent"
            :file-list="fileList"
            :multiple="false"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">&nbsp;请上传jpg/png文件，建议分辨率不要超过120*75、大小不超过1MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="分摊比例" prop="allocation_ratio">
          <el-input v-model="levelForm.allocation_ratio" :maxlength="3" clearable></el-input>
        </el-form-item>
        <el-form-item label="等级说明" prop="description">
          <en-rich-text-editor
            v-model="levelForm.description"
            :upload-api="MixinUploadApi"
            :upload-headers="MixinAccessToken"
            maxlength="9999"
          />
        </el-form-item>

        <el-divider>升级条件</el-divider>
        <div class="upgrade-item">
          <!-- <el-checkbox  v-model="levelForm.openPoint"></el-checkbox> -->
          <p class="span-text">积分</p>
          <el-input v-model="levelForm.point_condition_value_min" placeholder="请输入最小积分数" clearable></el-input>
          <span>至</span>
          <el-input v-model="levelForm.point_condition_value_max" placeholder="请输入最大积分数" clearable></el-input>
        </div>
        <!-- <div class="upgrade-item">
          <el-checkbox  v-model="levelForm.openAmount" @change=""></el-checkbox>
          <p class="span-text">消费金额</p>
          <el-input v-model="levelForm.amount_condition_value_min" placeholder="请输入最小金额" :maxlength="3" clearable></el-input>
          <span>至</span>
          <el-input v-model="levelForm.amount_condition_value_max" placeholder="请输入最大金额" :maxlength="3" clearable></el-input>
        </div> -->
        <el-divider>等级福利</el-divider>
        <!-- <div class="upgrade-item">
          <el-checkbox  v-model="levelForm.openGiftPoint" @change=""></el-checkbox>
          <p class="span-text">赠送积分</p>
          <el-input v-model="levelForm.point_benefit_value" placeholder="请输入1-100之间的整数" :maxlength="3" clearable></el-input>
        </div> -->
        <div class="upgrade-item">
          <!-- <el-checkbox  v-model="levelForm.openGiftAmount" @change=""></el-checkbox> -->
          <p class="span-text">消费折扣</p>
          <el-input v-model="levelForm.discount_benefit_value" placeholder="请输入1-100之间的整数" :maxlength="3" clearable>
            <template slot="append">%</template>
          </el-input>
        </div>
      </el-form>
      <div class="confirm-btn">
        <el-button  size="medium" type="primary" @click="handlerConfirm">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
    import { RegExp } from '~/ui-utils'
    import * as API_Member from '@/api/member'
    import { cloneObj } from '@/utils/index'
    import { UE } from '@/components'

    export default {
      name: 'coupon',
      components: { UE },
      data() {
        const checkNumber = (rule, value, callback) => {
          console.log(value)
          if (!value) {
            callback(new Error('请输入比例'))
          } else if (!RegExp.money.test(value)) {
            callback(new Error('请输入正整数'))
          } else if (value <= 0) {
            callback(new Error('分摊比例不能为0'))
          } else {
            callback()
          }
        }
        return {
          /** 添加，编辑  表单*/
          levelForm: {},
          fileList: [],
          /** 添加，编辑 表单规则*/
          levelRules: {
            level_name: [
              { required: true, message: '请输入等级名称', trigger: 'blur' }
            ],
            level_icon: [
              { required: true, message: '请上传图标' }
            ],

            allocation_ratio: [
              { required: true, message: '请输入分摊比例', trigger: 'blur' },
              { validator: checkNumber, trigger: 'blur' }
            ]
          },
          id: ''
        }
      },
      watch: {
        $route: {
          handler(val) {
            if (val.name === 'memberLevelEdit' && val.params.id) {
              this.id = val.params.id
              this.getMembersLevelDetail()
            } else if (val.name === 'memberLevelAdd') {
              this.levelForm = {}
            }
          },
          immediate: true
        }
      },
      methods: {
        uploadSuccess(res, file, fileList) {
          this.$set(this.levelForm, 'level_icon', res.url)
        },
        /** 图片移除之后 */
        delImgEvent() {
          this.fileList = []
          this.levelForm.level_icon = ''
        },
        /** 获取等级数据 */
        getMembersLevelDetail() {
          API_Member.getMembersLevelDetail(this.id).then(res => {
            const { upgrade_conditions, benefits } = res
            this.levelForm = cloneObj(res)
            this.$set(this.levelForm, 'point_condition_value_min', upgrade_conditions[0].condition_value_min)
            this.$set(this.levelForm, 'point_condition_value_max', upgrade_conditions[0].condition_value_max)
            this.$set(this.levelForm, 'discount_benefit_value', benefits[0].benefit_value)
            this.fileList = res.level_icon ? [{ name: 'level_icon', url: res.level_icon }] : []
          })
        },
        handlerConfirm() {
          this.$refs['levelForm'].validate((valid) => {
            if (valid) {
              const levelForm = cloneObj(this.levelForm)

              if (!levelForm.point_condition_value_min || !levelForm.point_condition_value_max) {
                this.$message.error('请填写升级积分条件！')
                return
              }
              if (!RegExp.integer.test(levelForm.point_condition_value_min) && parseInt(levelForm.point_condition_value_min) !== 0 || !RegExp.integer.test(levelForm.point_condition_value_max) && parseInt(levelForm.point_condition_value_max) !== 0) {
                this.$message.error('积分升级条件请填写正整数！')
                return
              }
              if (parseInt(levelForm.point_condition_value_min) > parseInt(levelForm.point_condition_value_max)) {
                this.$message.error('起始积分数不得大于最大积分数！')
                return
              }
              if (!RegExp.integer.test(levelForm.discount_benefit_value) && parseInt(levelForm.discount_benefit_value) !== 0) {
                this.$message.error('请正确填写消费折扣！')
                return
              }
              const params = {
                level_name: levelForm.level_name,
                level_icon: levelForm.level_icon,
                allocation_ratio: levelForm.allocation_ratio,
                description: levelForm.description,
                upgrade_conditions: [
                  {
                    condition_type: 'POINTS',
                    condition_value_min: levelForm.point_condition_value_min,
                    condition_value_max: levelForm.point_condition_value_max
                  }
                ],
                benefits: [
                  { benefit_type: 'DISCOUNT', benefit_value: levelForm.discount_benefit_value }
                ]
              }
              if (this.id) {
                API_Member.updateMembersLevel(this.id, params).then(res => {
                  this.$message.success('修改成功！')
                  this.$router.push({ name: 'memberLevel' })
                })
              } else {
                API_Member.addMembersLevel(params).then(res => {
                  this.$message.success('提交成功！')
                  this.$router.push({ name: 'memberLevel' })
                })
              }
            }
          })
        }
      }
    }
</script>

<style type="text/scss" lang="scss" scoped>
  /deep/ {
    .el-input {
      max-width: 400px;
    }
  }
  .level-content {
    background: #fff;
    padding: 20px;
    .confirm-btn {
      text-align: center;
      padding-top: 10px;
      margin-top: 10px;
      border-top: 1px dashed #DCDFE6;
    }
    .upgrade-item {
      font-size: 14px;
      font-weight: 700;
      color: #606266;
      margin: 20px;
      display: flex;
      align-items: center;
      .span-text {
        width: 65px;
        text-align: center;
      }
      .el-input {
        max-width: 200px;
        margin: 0 10px;
      }
    }
  }
</style>
